package com.redis.demo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author: zqf
 * @Date: 2022/10/19/21:08
 * @Description: redis 增删改查
 */
@RestController("/stringKey")
@Api(tags = "redis对字符串的操作")
public class StringRedisController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("addKey")
    @ApiOperation("添加key")
    public String addKey(@RequestParam("key") @ApiParam("key") String key,
                         @RequestParam("value") @ApiParam("value") String value) {
        stringRedisTemplate.opsForValue().set(key, value);
        return "添加成功";
    }


    @GetMapping("getValue")
    @ApiOperation("获取value")
    public String getKey(@RequestParam("key") @ApiParam("key") String key) {
        if (!stringRedisTemplate.hasKey(key)) {
            return "不存在该key";
        }
        return stringRedisTemplate.opsForValue().get(key);

    }

    @GetMapping("delKey")
    @ApiOperation("删除key")
    public String delKey(@RequestParam("key") @ApiParam("key") String key) {
        if (!stringRedisTemplate.hasKey(key)) {
            return "不存在该key";
        }
        Boolean delete = stringRedisTemplate.delete(key);
        if (delete) return "删除成功";
        return "删除失败";

    }


    @GetMapping("updateKey")
    @ApiOperation("修改value")
    public String updateKey(@RequestParam("key") @ApiParam("key") String key,
                            @RequestParam("value") @ApiParam("value") String value) {
        if (!stringRedisTemplate.hasKey(key)) {
            return "不存在该key";
        }
        stringRedisTemplate.opsForValue().set(key, value);
        return "修改成功";

    }

    @GetMapping("setByTime")
    @ApiOperation("设置过期时间")
    public String updateKey(@RequestParam("key") @ApiParam("key") String key,
                            @RequestParam("value") @ApiParam("value") String value,
                            @RequestParam("time") @ApiParam("time 单位秒") Long time) {
        stringRedisTemplate.opsForValue().set(key, value,time * 1000, TimeUnit.MILLISECONDS);
        return "设置成功";

    }
}